<?php

class Utility {

   public static function getWeekDates($date)
{
    $week =  date('W', strtotime($date));
    $year =  date('Y', strtotime($date));
    $from = date("Y-m-d", strtotime("{$year}-W{$week}-0")); 
    $to = date("Y-m-d", strtotime("{$year}-W{$week}-6"));   
   
    $ngayhomnay = date("Y-m-d"); // Năm/Tháng/Ngày
    if (strtotime($ngayhomnay) > strtotime($to)) {
    return false;
    }elseif (strtotime($ngayhomnay) == strtotime($to)) {
     return true;
    }else{
     return true;
    }
}
    
    public static function fillSelectBox_Day($xtemplate, $block, $selectedID = null) {
        for ($i = 1; $i <= 31; $i++) {
            $xtemplate->assign('ID', $i);
            $xtemplate->assign('VALUE', $i);

            if ($selectedID != null) {
                if ($selectedID == $i) {
                    $xtemplate->assign('SELECTED', 'selected');
                } else {
                    $xtemplate->assign('SELECTED', '');
                }
            }
            $xtemplate->parse($block);
        }
    }

    public static function fillSelectBox_Month($xtemplate, $block, $selectedID = null) {
        for ($i = 1; $i <= 12; $i++) {
            $xtemplate->assign('ID', $i);
            $xtemplate->assign('VALUE', $i);

            if ($selectedID != null) {
                if ($selectedID == $i) {
                    $xtemplate->assign('SELECTED', 'selected');
                } else {
                    $xtemplate->assign('SELECTED', '');
                }
            }
            $xtemplate->parse($block);
        }
    }

    public static function base64url_encode($plainText) {
        $base64 = base64_encode($plainText);
        $base64url = strtr($base64, '+/=', '-_,');
        return $base64url;
    }

    public static function base64url_decode($plainText) {
        $base64url = strtr($plainText, '-_,', '+/=');
        $base64 = base64_decode($base64url);
        return $base64;
    }

    // ham chuyen trang 
    public static function redirect($url) {
        if ($url == 'back') {
            echo "<script>window.history.back(2)</script>\n";
        } else {
            /* kiem tra neu header already by send thi chuyen trang = script nguoc lai chuyen trang = code server */
            if (headers_sent()) {
                echo "<script>document.location.href='$url';</script>\n";
            } else {
                ob_end_clean(); // clear output buffer
                header('HTTP/1.1 301 Moved Permanently');
                header("Location: $url");
            }
        }
        exit();
    }

    // ham dinh dang kieu ngay thang thang trong mysql
    public static function formatDateTime($date, $hour = null, $minute = null) {
        if ($hour == null && $minute == null) {
            return substr($date, -4) . "/" . substr($date, 3, 2) . "/" . substr($date, 0, 2) . " " . date('h:i:s');
        } else {
            return substr($date, -4) . "/" . substr($date, 3, 2) . "/" . substr($date, 0, 2) . " " . $hour . ':' . $minute . ':00';
        }
    }

    // chuyen kieu ngay thang trong mysql de hien thi ra ngoai
    public static function formatDateTimeToView($date, $haveTime = false) {
        if ($haveTime == true) {
            return substr($date, 11, 5) . ' - ' . substr($date, 8, 2) . "/" . substr($date, 5, 2) . "/" . substr($date, 0, 4);
        } else {
            return substr($date, 8, 2) . "/" . substr($date, 5, 2) . "/" . substr($date, 0, 4);
        }
    }

    // ham go bo dau cua 1 chuoi
    public static function removeSigns($text) {
        $unicode = array(
            'a' => 'ä|à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ',
            'd' => 'đ',
            'e' => 'è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ',
            'i' => 'ì|í|î|ị|ỉ|ĩ',
            'o' => 'ö|ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ',
            'u' => 'ü|ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ',
            'y' => 'ỳ|ý|ỵ|ỷ|ỹ',
            'A' => 'Ä|À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ',
            'D' => 'Ð',
            'E' => 'È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ',
            'I' => 'Ì|Í|Ị|Ỉ|Ĩ',
            'O' => 'Ö|Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ',
            'U' => 'Ü|Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ',
            'Y' => 'Ỳ|Ý|Ỵ|Ỷ|Ỹ',
        );

        foreach ($unicode as $nonUnicode => $uni) {
            $text = preg_replace("/($uni)/i", $nonUnicode, $text);
        }
        $text = str_replace('ç', 'c', $text);
        $text = str_replace('Ç', 'C', $text);
        $text = str_replace(' / ', '-', $text);
        $text = str_replace('/', '-', $text);
        $text = str_replace(' - ', '-', $text);
        $text = str_replace('_', '-', $text);
        $text = str_replace(' ', '-', $text);
        $text = str_replace(',', '-', $text);
        $text = str_replace('.', '-', $text);
        $text = str_replace('ß', 'ss', $text);
        $text = str_replace('&amp;', '', $text);
        $text = str_replace('%', '', $text);
        $text = preg_replace('[^A-Za-z0-9]', '', $text);

        return $text;
    }

    public static function replaceHtmlSpecialChars($t = "") {
        $t = str_replace("\\", "", $t);
        return $t;
    }

    // kiem tra duoi file co hop le
    public static function checkFileExtension($valid_formats, $ext) {
        if (in_array($ext, $valid_formats)) {
            return false;
        }
    }

    // hàm tạo session
    public static function createSession($names, $values) {
        //session_start();

        if ($names != null) {
            // tương ứng với mỗi giá trị trong mảng tên thì sẽ tạo ra 1 session
            for ($i = 0; $i < count($names); $i++) {
                $_SESSION[$names[$i]] = $values[$i];
            }
        }
    }

    // hàm hủy session
    public static function destroySession() {
        //session_start();
        session_unset();
    }

    // hiển thị thông báo
    public static function messageBox($message, $url = null) {
        echo '<script language="javascript" type="text/javascript">';
        echo 'alert("' . $message . '");';
        if ($url != null) {
            echo 'document.location.href="' . $url . '"';
        }
        echo '</script>';
    }

    public static function reload() {
        echo "<script>window.location.reload();</script>";
    }

    /**
     * hàm cắt chuỗi theo độ dài
     * @param type $string: chuỗi gốc muốn cắt
     * @param type $lenghtToCut: độ dài muốn cắt
     * @param type $endcode: chuỗi có phải unicode không
     * @return string: chuỗi sau khi được cắt     
     */
    public static function subString($string, $lenghtToCut, $endcode) {

        if ($endcode == true) {

            if (mb_strlen($string, 'UTF-8') > $lenghtToCut) {

                $string = mb_substr($string, 0, $lenghtToCut, 'UTF-8');

                $lenght = mb_strlen($string, 'UTF-8');

                // cắt bỏ các ký tự dư thừa
                while (mb_substr($string, $lenght - 1, $lenght, 'UTF-8') != ' ') {
                    $lenght--;
                    $string = mb_substr($string, 0, $lenght, 'UTF-8');
                }
                return $string . '...';
            } else {

                return $string;
            }
        } else {

            $string = substr($string, 0, $lenghtToCut);

            $lenght = strlen($string);

            // cắt bỏ các ký tự dư thừa
            while (substr($string, $lenght - 1, $lenght) != ' ') {
                $lenght--;
                $string = substr($string, 0, $lenght);
            }

            $string = $string . '...';

            return $string;
        }
    }

    // hàm tải chuỗi html hiển thị danh sách chọn số lượng dòng hiển thị
    public static function getLimitList($rowToView) {
        $limitListHTML = '';
        // tải danh sách chọn số dòng hiển thị trên trang
        for ($j = 5; $j <= 50; $j = $j + 5) {
            // nếu có biến post categoryID 
            // (tức là có chọn thì hiển thị lại cái đã chọn trong danh sách)
            if ($rowToView == $j) {
                $limitListHTML .= "<option value='$j' selected>$j</option>";
            } else {
                $limitListHTML .= "<option value='$j'>$j</option>";
            }
        }
        return $limitListHTML;
    }

    /**
     * format a number to currency string
     * @param type $number: number to format
     * @return type string: currency string
     */
    public static function formatToCurrencyString($number) {
        return number_format($number, 0, ',', '.');
    }

    public static function getCurrentDate() {
        date_default_timezone_set('Asia/Ho_Chi_Minh');
        return date('Y-m-d');
    }

    public static function daysBetweenDate($beginDate, $endDate) {
        $fromDate = date('Y-m-d', strtotime($beginDate));
        $toDate = date('Y-m-d', strtotime($endDate));

        $date_parts1 = explode('-', $fromDate);
        $date_parts2 = explode('-', $toDate);

        // Converts a Gregorian date to Julian Day Count
        $start_date = gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
        $end_date = gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
        return $end_date - $start_date;
    }

    public static function addToCart($itemID, $itemPrice, $quantity, $strProperty) {

        // total price of an item
        $totalPrice = $itemPrice * $quantity;

        // array of property
        $arrayProperty = array();


        if ($strProperty != '') {
            // convert string to array of property

            $properties = array();

            $properties = explode(',', $strProperty);

            for ($i = 0; $i < count($properties); $i++) {
                //property id
                $arrayProperty[$i][0] = $properties[$i];
                // is already
                $arrayProperty[$i][1] = '';
            }
        }


        // if exist 'cart session'
        if (isset($_SESSION['cart']) && count($_SESSION['cart']) > 0) {

            $isAlready = false;

            // UPDATE QUANTITY IF EXIST ITEM
            // ELSE ADD AN ITEM TO ARRAY
            for ($i = 0; $i < count($_SESSION['cart']); $i++) {
                // if exist array property
                if (count($arrayProperty) > 0) {
                    // loop each property and check the existence of the item (with property) in cart
                    // if exist then increase quantity
                    for ($y = 0; $y < count($arrayProperty); $y++) {
                        // loop each item in cart to check already
                        if ($_SESSION['cart'][$i]['itemID'] == $itemID && $_SESSION['cart'][$i]['propertyID'] == $arrayProperty[$y][0]) {
                            $_SESSION['cart'][$i]['quantity'] = $_SESSION['cart'][$i]['quantity'] + $quantity;
                            $_SESSION['cart'][$i]['totalEachItem'] = $_SESSION['cart'][$i]['totalEachItem'] + $totalPrice;
                            // is already
                            $arrayProperty[$y][1] = 1;
                        }
                    }
                } else {
                    // if exist the item
                    if ($_SESSION['cart'][$i]['itemID'] == $itemID && $_SESSION['cart'][$i]['propertyID'] == '') {
                        $_SESSION['cart'][$i]['quantity'] = $_SESSION['cart'][$i]['quantity'] + $quantity;
                        $_SESSION['cart'][$i]['totalEachItem'] = $_SESSION['cart'][$i]['totalEachItem'] + $totalPrice;
                        $isAlready = true;
                        break;
                    }
                }
            }

            if (count($arrayProperty) > 0) {
                // loop each property then add new item into cart if not exist
                for ($y = 0; $y < count($arrayProperty); $y++) {
                    if ($arrayProperty[$y][1] != 1) {
                        $_SESSION['cart'][] = array('itemID' => $itemID, 'totalEachItem' => $totalPrice, 'quantity' => $quantity, 'propertyID' => $arrayProperty[$y][0], 'itemPrice' => $itemPrice);
                    }
                }
            } else if ($isAlready == false) {
                $_SESSION['cart'][] = array('itemID' => $itemID, 'totalEachItem' => $totalPrice, 'quantity' => $quantity, 'propertyID' => '', 'itemPrice' => $itemPrice);
            }
        } else {
            // if exist array property
            if (count($arrayProperty) > 0) {
                // each property corresponding to one product
                for ($i = 0; $i < count($arrayProperty); $i++) {
                    $_SESSION['cart'][] = array('itemID' => $itemID, 'totalEachItem' => $totalPrice, 'quantity' => $quantity, 'propertyID' => $arrayProperty[$i][0], 'itemPrice' => $itemPrice);
                }
            } else {
                $_SESSION['cart'][] = array('itemID' => $itemID, 'totalEachItem' => $totalPrice, 'quantity' => $quantity, 'propertyID' => '', 'itemPrice' => $itemPrice);
            }
        }
    }

    public static function checkStringIn($stringIn, $string) {
        if (strpos($string, $stringIn) !== FALSE) {
            return true;
        } else {
            return false;
        }
    }

    public static function checkPermission($action, $groupFunctions, $functionID) {
        for ($i = 0; $i < count($groupFunctions); $i++) {

            if ($groupFunctions[$i]['functionID'] == $functionID) {
                switch ($action) {
                    case 'view':
                        if ($groupFunctions[$i]['view'] == 1) {
                            return true;
                        } else {
                            return false;
                        }
                        break;
                    case 'add':
                        if ($groupFunctions[$i]['add'] == 1) {
                            return true;
                        } else {
                            return false;
                        }
                        break;
                    case 'delete':
                        if ($groupFunctions[$i]['delete'] == 1) {
                            return true;
                        } else {
                            return false;
                        }
                        break;
                    case 'update':
                        if ($groupFunctions[$i]['update'] == 1) {
                            return true;
                        } else {
                            return false;
                        }
                        break;
                    case 'disable':
                        if ($groupFunctions[$i]['disable'] == 1) {
                            return true;
                        } else {
                            return false;
                        }
                        break;
                    case 'enable':
                        if ($groupFunctions[$i]['enable'] == 1) {
                            return true;
                        } else {
                            return false;
                        }
                        break;
                    case 'highlight':
                        if ($groupFunctions[$i]['highlight'] == 1) {
                            return true;
                        } else {
                            return false;
                        }
                        break;
                    case 'unhighlight':
                        if ($groupFunctions[$i]['unhighlight'] == 1) {
                            return true;
                        } else {
                            return false;
                        }
                        break;
                }
                break;
            }
        }
    }

    public static function createGUID($namespace = '') {
        static $guid = '';
        $uid = uniqid("", true);
        $data = $namespace;
        $data .= $_SERVER['REQUEST_TIME'];  // The timestamp of the start of the request
        $data .= $_SERVER['HTTP_USER_AGENT'];   // A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586)
        $data .= $_SERVER['REMOTE_ADDR'];   // The IP address from which the user is viewing the current page. 
        $data .= $_SERVER['REMOTE_PORT'];   // The port being used on the user's machine to communicate with the web server
        $hash = strtolower(hash('ripemd128', $uid . $guid . md5($data)));
        $guid = substr($hash, 0, 8) .
                '-' .
                substr($hash, 8, 4) .
                '-' .
                substr($hash, 12, 4) .
                '-' .
                substr($hash, 16, 4) .
                '-' .
                substr($hash, 20, 12);
        return $guid;
    }

    // gan noi dung file vao 1 bien
    public static function assignFileContentToVariable($file) {
        ob_start(); // start buffer
        include($file);
        $content = ob_get_contents(); // assign buffer contents to variable
        ob_end_clean(); // end buffer and remove buffer contents

        return $content;
    }

}

?>